package com.colorful.insuranceproject.claims;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.colorful.insuranceproject.R;
import com.colorful.insuranceproject.base.TitleActivity;
import com.colorful.insuranceproject.bean.UploadDetailsBean;
import com.colorful.insuranceproject.commonActivity.WebViewActivity;
import com.colorful.insuranceproject.consts.CodeTable;
import com.colorful.insuranceproject.consts.URLConst;
import com.colorful.insuranceproject.request.ClaimsRequest;
import com.lovely3x.common.beans.HeaderBean;
import com.lovely3x.common.image.displayer.ImgBrowserPagerAdapter;
import com.lovely3x.common.utils.Response;
import com.lovely3x.imageloader.ImageLoader;
import com.nostra13.universalimageloader.core.download.ImageDownloader;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by handsome-Bob on 2017/8/18.
 * <p>
 * 步骤二 票据上传
 */
public class ClaimsStepTwoActivity extends TitleActivity implements TextWatcher {

    public static final String EXTRA_STATUS = "EXTRA_STATUS";

    private ClaimsRequest claimsRequest;

    private static final int HANDLER_WHAT_UPLOAD_INVOICE = 0X1;

    private static final int HANDLER_WHAT_UPLOAD_DRUG_LIST = 0X2;

    private static final int HANDLER_WHAT_UPLOAD_OTHER = 0X3;

    private static final int UPLOAD_PAPER_URL = 0X4;

    private static final int SUPPLEMENT_UPLOAD = 0X5;

    private static final int REQUEST_CODE_CHOICE_IMG = 0x7;

    private static final int REQUEST_CODE_CHOICE_IMG_DETAILS = 0X8;

    private static final int REQUEST_CODE_CHOICE_IMG_OTHER = 0X9;

    public static final int MAX_IMG_NUM = 5;

    public static final String EXTRA_DATE = "extra_date";

    public static final String EXTRA_NAME = "extra_name";

    public static final String EXTRA_UPLOAD_BEAN = "extra_upload_bean";

    private ArrayList<String> chociedImgs = new ArrayList<>();

    private ArrayList<String> chociedImgsDetials = new ArrayList<>();

    private ArrayList<String> chociedImgsOther = new ArrayList<>();

    private static final String RESTORE_KEY_IMGS = "restore.key.imgs";

    private static final String RESTORE_KEY_IMGS_DETAILS = "restore.key.imgs.details";

    private static final String RESTORE_KEY_IMGS_OTHER = "restore.key.imgs.other";

    @Bind(R.id.iv_activity_evaluation_imgs_container)
    LinearLayout llImgsContainer;

    @Bind(R.id.iv_activity_evaluation_imgs_container_details)
    LinearLayout llImgsContainerDetails;

    @Bind(R.id.iv_activity_evaluation_imgs_container_other)
    LinearLayout llImgsContainerOther;

    @Bind(R.id.iv_activity_evaluation_add_plus)
    ImageView ivAddPlus;

    @Bind(R.id.iv_activity_evaluation_add_plus_details)
    ImageView ivAddPlusDetails;

    @Bind(R.id.iv_activity_evaluation_add_plus_other)
    ImageView ivAddPlusOther;

    /**
     * 发票日期
     */
    @Bind(R.id.tv_date)
    TextView tvDate;

    /**
     * 申请金额
     */
    @Bind(R.id.et_money)
    EditText etMoney;

    @Bind(R.id.ll_remarks)
    LinearLayout llRemarks;

    @Bind(R.id.tv_remarks)
    TextView tvRemarks;

    private String date;

    List<String> listOne;

    List<String> listTwo;

    List<String> listThree;

    List<String> uploadOne;

    List<String> uploadTwo;

    List<String> uploadThree;

    private int PicLength;

    List<String> failLength;

    UploadDetailsBean ub;

    private int status;

    @Override
    protected int getContentView() {
        return R.layout.activity_claims_step_two;
    }

    @Override
    protected void initViews() {
        ButterKnife.bind(this);
        setTitle(getString(R.string.step_two));
    }

    @Override
    protected void onViewInitialized() {
        claimsRequest = new ClaimsRequest(getHandler());
        etMoney.addTextChangedListener(this);
        tvDate.setText(date);
        PicLength = 0;
        failLength = new ArrayList<>();
        listOne = new ArrayList<>();
        listTwo = new ArrayList<>();
        listThree = new ArrayList<>();
        uploadOne = new ArrayList<>();
        uploadTwo = new ArrayList<>();
        uploadThree = new ArrayList<>();

        //  如果是重列表页跳转过来  那么我们就加载页面数据
        if (ub != null) {
            if (status == 3) {
                llRemarks.setVisibility(View.VISIBLE);
                tvRemarks.setText(getString(R.string.apply_fail_reson, ub.getReason()));// 失败原因
            }
            tvDate.setText(ub.getPaperTime());
            etMoney.setText(ub.getApplyMoney());
            if (ub.getPaperImgs1() != null) {
                chociedImgs.addAll(ub.getPaperImgs1());
                refreshImageBar(REQUEST_CODE_CHOICE_IMG);
            }
            if (ub.getPaperImgs2() != null && !ub.getPaperImgs2().isEmpty()) {
                chociedImgsDetials.addAll(ub.getPaperImgs2());
                refreshImageBarDetails(REQUEST_CODE_CHOICE_IMG_DETAILS);
            }
            if (ub.getPaperImgs3() != null && !ub.getPaperImgs3().isEmpty()) {
                chociedImgsOther.addAll(ub.getPaperImgs3());
                refreshImageBarOther(REQUEST_CODE_CHOICE_IMG_OTHER);
            }
        }
    }

    private void refreshImageBar(int request) {
        llImgsContainer.removeAllViews();
        ivAddPlus.setVisibility(chociedImgs.size() >= MAX_IMG_NUM ? View.GONE : View.VISIBLE);
        for (int i = 0; i < chociedImgs.size(); i++) {
            String path = chociedImgs.get(i);
            displayUri(path, i, request);
        }
    }

    private void refreshImageBarDetails(int request) {
        llImgsContainerDetails.removeAllViews();
        ivAddPlusDetails.setVisibility(chociedImgsDetials.size() >= MAX_IMG_NUM ? View.GONE : View.VISIBLE);
        for (int i = 0; i < chociedImgsDetials.size(); i++) {
            String path = chociedImgsDetials.get(i);
            displayUri(path, i, request);
        }
    }

    private void refreshImageBarOther(int request) {
        llImgsContainerOther.removeAllViews();
        ivAddPlusOther.setVisibility(chociedImgsOther.size() >= MAX_IMG_NUM ? View.GONE : View.VISIBLE);
        for (int i = 0; i < chociedImgsOther.size(); i++) {
            String path = chociedImgsOther.get(i);
            displayUri(path, i, request);
        }
    }

    @Override
    protected void onInitExtras(@NonNull Bundle bundle) {
        super.onInitExtras(bundle);
        date = bundle.getString(EXTRA_DATE);
        ub = bundle.getParcelable(EXTRA_UPLOAD_BEAN);
        status = bundle.getInt(EXTRA_STATUS);
    }

    @Override
    public void restoreInstanceOnCreateBefore(@NonNull Bundle savedInstance) {
        ArrayList<String> imgs = savedInstance.getStringArrayList(RESTORE_KEY_IMGS);
        if (imgs != null && !imgs.isEmpty()) {
            chociedImgs.clear();
            chociedImgs.addAll(imgs);
        }

        ArrayList<String> imgsDetails = savedInstance.getStringArrayList(RESTORE_KEY_IMGS_DETAILS);
        if (imgsDetails != null && !imgsDetails.isEmpty()) {
            chociedImgsDetials.clear();
            chociedImgsDetials.addAll(imgsDetails);
        }

        ArrayList<String> imgsOther = savedInstance.getStringArrayList(RESTORE_KEY_IMGS_OTHER);
        if (imgsOther != null && !imgsOther.isEmpty()) {
            chociedImgsOther.clear();
            chociedImgsOther.addAll(imgsOther);
        }
    }

    @Override
    public void restoreInstanceOnCreateAfter(@NonNull Bundle savedInstance) {

    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putStringArrayList(RESTORE_KEY_IMGS, chociedImgs);
        outState.putStringArrayList(RESTORE_KEY_IMGS_DETAILS, chociedImgsDetials);
        outState.putStringArrayList(RESTORE_KEY_IMGS_OTHER, chociedImgsOther);
    }

    @OnClick({R.id.tv_set, R.id.tv_upload_invoice_encounter_question, R.id.iv_activity_evaluation_add_plus,
            R.id.iv_activity_evaluation_add_plus_details, R.id.iv_activity_evaluation_add_plus_other})
    void OnClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_set:
                loadData();
                break;
            case R.id.tv_upload_invoice_encounter_question:
                String url = URLConst.UPLOAD_INVOICE_ENCOUNTER_QUESTION;
                launchActivity(WebViewActivity.class, WebViewActivity.EXTRA_LOAD_URL, url);
                break;
            // 上传发票被点击
            case R.id.iv_activity_evaluation_add_plus:
                showChoiceImageDialog(REQUEST_CODE_CHOICE_IMG, false);
                break;
            //  请上传药品清单
            case R.id.iv_activity_evaluation_add_plus_details:
                showChoiceImageDialog(REQUEST_CODE_CHOICE_IMG_DETAILS, false);
                break;
            //  其他
            case R.id.iv_activity_evaluation_add_plus_other:
                showChoiceImageDialog(REQUEST_CODE_CHOICE_IMG_OTHER, false);
                break;
        }
    }

    /**
     * 上传资料
     */
    private void loadData() {
        if (chociedImgs.size() < 1) {
            showToast(getString(R.string.invoice_must_be_uploaded));
        } else if (etMoney.getText().toString().trim().equals("")) {
            showToast(getString(R.string.please_input_claims_money));
        } else {
            PicLength = chociedImgs.size() + chociedImgsDetials.size() + chociedImgsOther.size();

            showProgressCircle(getString(R.string.upload_data));

            List<String> uploadJudge = new ArrayList<>();

            for (String list : chociedImgs) {
                if (!list.startsWith("http"))
                    uploadJudge.add("1");
            }

            for (String list : chociedImgsDetials) {
                if (!list.startsWith("http"))
                    uploadJudge.add("1");
            }

            for (String list : chociedImgsOther) {
                if (!list.startsWith("http"))
                    uploadJudge.add("1");
            }

            if (uploadJudge.size() == 0 && status != 0) {

                if (uploadJudge.size() == 0) {
                    String date = tvDate.getText().toString().trim();
                    String money = etMoney.getText().toString().trim();

                    String stringOne = "";
                    String stringTwo = "";
                    String stringThree = "";

                    for (String list : ub.getPaperImgs1()) {
                        stringOne += list + ",";
                    }

                    for (String list : ub.getPaperImgs2()) {
                        stringTwo += list + ",";
                    }

                    for (String list : ub.getPaperImgs3()) {
                        stringThree += list + ",";
                    }

                    if (status == 1 || status == 3) {//  补充
                        claimsRequest.supplementUpload(ub.getInsuranceId(), money, date, stringOne, stringTwo, stringThree, SUPPLEMENT_UPLOAD);
                    } else {
                        claimsRequest.paperUpload(date, money, stringOne, stringTwo, stringThree, UPLOAD_PAPER_URL);
                    }
                }
            } else {
                //  上传发票
                for (String lists : chociedImgs) {
                    List<String> list = new ArrayList<>();
                    if (!lists.startsWith("http")) {
                        list.add(lists);
                        claimsRequest.uploadMultiFiles(list, "dynamic", HANDLER_WHAT_UPLOAD_INVOICE);
                    } else {
                        uploadOne.add(lists);
                    }
                }

                //  上传药品清单
                for (String list : chociedImgsDetials) {
                    List<String> listDrug = new ArrayList<>();
                    if (!list.startsWith("http")) {
                        listDrug.add(list);
                        claimsRequest.uploadMultiFiles(listDrug, "dynamic", HANDLER_WHAT_UPLOAD_DRUG_LIST);
                    } else {
                        uploadTwo.add(list);
                    }
                }

                //  上传其他
                for (String list : chociedImgsOther) {
                    List<String> listOther = new ArrayList<>();
                    if (!list.startsWith("http")) {
                        listOther.add(list);
                        claimsRequest.uploadMultiFiles(listOther, "dynamic", HANDLER_WHAT_UPLOAD_OTHER);
                    } else {
                        uploadThree.add(list);
                    }
                }
            }
        }
    }

    @Override
    protected void handleResponseMessage(Message msg, Response response) {
        super.handleResponseMessage(msg, response);
        switch (msg.what) {
            case HANDLER_WHAT_UPLOAD_INVOICE:// 上传发票
                if (response.isSuccessful) {
                    HeaderBean headerBean = (HeaderBean) response.obj;
                    listOne.add(headerBean.getDomain() + headerBean.getSavePath() + headerBean.getName());
                    isUpload();
                } else {
                    failLength.add("1");
                    showToast(CodeTable.getInstance().getCodeDescription(response));
                }
                break;
            case HANDLER_WHAT_UPLOAD_DRUG_LIST:// 上传药品清单
                if (response.isSuccessful) {
                    HeaderBean headerBean = (HeaderBean) response.obj;
                    listTwo.add(headerBean.getDomain() + headerBean.getSavePath() + headerBean.getName());
                    isUpload();
                } else {
                    failLength.add("1");
                    showToast(CodeTable.getInstance().getCodeDescription(response));
                }
                break;
            case HANDLER_WHAT_UPLOAD_OTHER:// 上传其他
                if (response.isSuccessful) {
                    HeaderBean headerBean = (HeaderBean) response.obj;
                    listThree.add(headerBean.getDomain() + headerBean.getSavePath() + headerBean.getName());
                    isUpload();
                } else {
                    failLength.add("1");
                    showToast(CodeTable.getInstance().getCodeDescription(response));
                }
                break;

            case UPLOAD_PAPER_URL:// 上传票据
                dismissProgressCircle();
                if (response.isSuccessful) {
                    String id = response.obj.toString();
                    launchActivityForResult(ClaimsStepThreeActivity.class, 10000, ClaimsStepThreeActivity.EXTRA_CLAIMS_ID, id);
                } else {
                    showToast(CodeTable.getInstance().getCodeDescription(response));
                }

                break;

            case SUPPLEMENT_UPLOAD:
                dismissProgressCircle();
                if (status == 1) {//  补充
                    showToast(getString(R.string.Data_complement_success));
                } else {
                    showToast(getString(R.string.Data_edit_success));
                }
                finish();
                break;
        }
    }

    private void isUpload() {
        if ((listOne.size() + listTwo.size() + listThree.size() + failLength.size() + uploadOne.size() + uploadTwo.size() + uploadThree.size()) == PicLength) {
            if (failLength.size() > 0) {
                showToast(getString(R.string.pic_load_fail));
                dismissProgressCircle();
            } else {
                String time = tvDate.getText().toString();
                String money = etMoney.getText().toString();
                String stringOne = "";
                String stringTwo = "";
                String stringThree = "";

                listOne.addAll(uploadOne);
                listTwo.addAll(uploadTwo);
                listThree.addAll(uploadThree);

                for (String list : listOne) {
                    stringOne += list + ",";
                }

                for (String list : listTwo) {
                    stringTwo += list + ",";
                }

                for (String list : listThree) {
                    stringThree += list + ",";
                }

                if (status == 1 || status == 3) {//  补充
                    claimsRequest.supplementUpload(ub.getInsuranceId(), money, time, stringOne, stringTwo, stringThree, SUPPLEMENT_UPLOAD);
                } else {
                    claimsRequest.paperUpload(time, money, stringOne, stringTwo, stringThree, UPLOAD_PAPER_URL);
                }
            }
        }
    }

    /**
     * 重建图片视图表
     */
    protected void rebuildImgs(int request) {
        if (request == REQUEST_CODE_CHOICE_IMG) {
            refreshImageBar(request);
        } else if (request == REQUEST_CODE_CHOICE_IMG_DETAILS) {
            refreshImageBarDetails(request);
        } else if (request == REQUEST_CODE_CHOICE_IMG_OTHER) {
            refreshImageBarOther(request);
        }
    }

    /**
     * 显示图片
     *
     * @param path  需要显示的地址
     * @param index 下标
     */
    private void displayUri(String path, final int index, final int request) {
        View itemView = getLayoutInflater().inflate(R.layout.view_pic_delete, llImgsContainer, false);

        ImageView ivPic = (ImageView) itemView.findViewById(R.id.iv_view_pic_pic);//图片
        View ivDel = itemView.findViewById(R.id.iv_view_pic_del);//删除

        if (path.startsWith("http")) {
            ImageLoader.getInstance().display(ivPic, path);
        } else {
            ImageLoader.getInstance().display(ivPic, ImageDownloader.Scheme.FILE.wrap(path));
        }

        /*
         *  查看图片
         */
        ivPic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (request == REQUEST_CODE_CHOICE_IMG)
                    showImgOnNewActivity(chociedImgs, ImgBrowserPagerAdapter.IMG_SOURCE_TYPE_FILE, index);
                else if (request == REQUEST_CODE_CHOICE_IMG_DETAILS)
                    showImgOnNewActivity(chociedImgsDetials, ImgBrowserPagerAdapter.IMG_SOURCE_TYPE_FILE, index);
                else if (request == REQUEST_CODE_CHOICE_IMG_OTHER)
                    showImgOnNewActivity(chociedImgsOther, ImgBrowserPagerAdapter.IMG_SOURCE_TYPE_FILE, index);
            }
        });

        /*
         * 删除选中的图片
         */
        ivDel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showConfirmDialog(R.string.delete_the_pic, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (request == REQUEST_CODE_CHOICE_IMG) {
                            chociedImgs.remove(index);
                            rebuildImgs(REQUEST_CODE_CHOICE_IMG);
                        } else if (request == REQUEST_CODE_CHOICE_IMG_DETAILS) {
                            chociedImgsDetials.remove(index);
                            rebuildImgs(REQUEST_CODE_CHOICE_IMG_DETAILS);
                        } else if (request == REQUEST_CODE_CHOICE_IMG_OTHER) {
                            chociedImgsOther.remove(index);
                            rebuildImgs(REQUEST_CODE_CHOICE_IMG_OTHER);
                        }
                    }
                });
            }
        });

        if (request == REQUEST_CODE_CHOICE_IMG) {
            llImgsContainer.addView(itemView);
        } else if (request == REQUEST_CODE_CHOICE_IMG_DETAILS) {
            llImgsContainerDetails.addView(itemView);
        } else if (request == REQUEST_CODE_CHOICE_IMG_OTHER) {
            llImgsContainerOther.addView(itemView);
        }
    }

    /**
     * 选择图片后的回调
     *
     * @param uri 选择的图片的地址
     */
    @Override
    protected void onImageSelected(Uri uri, int requestCode) {
        super.onImageSelected(uri, requestCode);
        if (requestCode == REQUEST_CODE_CHOICE_IMG) {
            if (chociedImgs.size() < MAX_IMG_NUM) {
                String path = uri.getPath();
                chociedImgs.add(uri.getPath());
                displayUri(path, chociedImgs.size() - 1, REQUEST_CODE_CHOICE_IMG);
            }
            ivAddPlus.setVisibility(chociedImgs.size() >= MAX_IMG_NUM ? View.GONE : View.VISIBLE);
        } else if (requestCode == REQUEST_CODE_CHOICE_IMG_DETAILS) {
            if (chociedImgsDetials.size() < MAX_IMG_NUM) {
                String path = uri.getPath();
                chociedImgsDetials.add(uri.getPath());
                displayUri(path, chociedImgsDetials.size() - 1, REQUEST_CODE_CHOICE_IMG_DETAILS);
            }
            ivAddPlusDetails.setVisibility(chociedImgsDetials.size() >= MAX_IMG_NUM ? View.GONE : View.VISIBLE);
        } else if (requestCode == REQUEST_CODE_CHOICE_IMG_OTHER) {
            if (chociedImgsOther.size() < MAX_IMG_NUM) {
                String path = uri.getPath();
                chociedImgsOther.add(uri.getPath());
                displayUri(path, chociedImgsOther.size() - 1, REQUEST_CODE_CHOICE_IMG_OTHER);
            }
            ivAddPlusOther.setVisibility(chociedImgsOther.size() >= MAX_IMG_NUM ? View.GONE : View.VISIBLE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10000 && resultCode == RESULT_OK) {
            setResult(RESULT_OK);
            finish();
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (s.toString().contains(".")) {
            if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                s = s.toString().subSequence(0,
                        s.toString().indexOf(".") + 3);
                etMoney.setText(s);
                etMoney.setSelection(s.length());
            }
        }
        if (s.toString().substring(0).equals(".")) {
            s = "0" + s;
            etMoney.setText(s);
            etMoney.setSelection(2);
        }

        if (s.toString().startsWith("0") && s.toString().trim().length() > 1) {
            if (!s.toString().substring(1, 2).equals(".")) {
                etMoney.setText(s.subSequence(0, 1));
                etMoney.setSelection(1);
                return;
            }
        }

        String text = etMoney.getText().toString();
        if (text.indexOf(".", text.indexOf(".") + 1) > 0) {
            text = text.substring(0, text.length() - 1);
            etMoney.setText(text);
            etMoney.setSelection(text.length());
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }
}
